package com.example.cardmatchinggame;

import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> {
    private CardMatchingGame game;
    private OnCardClickListener listener;

    public interface OnCardClickListener {
        void onCardClick(int position);
    }

    public CardAdapter(CardMatchingGame game, OnCardClickListener listener) {
        this.game = game;
        this.listener = listener;
    }

    @NonNull
    @Override
    public CardViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_card, parent, false);
        return new CardViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CardViewHolder holder, int position) {
        Card card = game.cardAtIndex(position);
        
        if (card.isMatched()) {
            holder.cardText.setText("");
            holder.cardText.setBackgroundColor(Color.parseColor("#4CAF50"));
        } else if (card.isFaceUp()) {
            holder.cardText.setText(card.getContent());
            holder.cardText.setBackgroundColor(Color.parseColor("#FF9800"));
        } else {
            holder.cardText.setText(R.string.card_back);
            holder.cardText.setBackgroundColor(Color.parseColor("#2196F3"));
        }

        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onCardClick(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return game.getCardCount();
    }

    static class CardViewHolder extends RecyclerView.ViewHolder {
        TextView cardText;

        CardViewHolder(@NonNull View itemView) {
            super(itemView);
            cardText = itemView.findViewById(R.id.tv_card);
        }
    }
}
